<template>
  <div class="chatRoom">
    <aside>
      <p class="title">30天内联系人</p>
      <GeminiScrollbar class="bar" :autoshow="true">
        <ul>
          <li
            v-for="contect of contects"
            :key="contect.id"
            :class="{ active: nowName === contect.name }"
            @click="changePerson(contect)">
            <img v-if="contect.headpic !== ''"
              class="thumb"
              width="43"
              height="43"
              :src="contect.headpic">
            <img v-else class="thumb" width="43" height="43" src="@/assets/img/default.png">
            <div class="contect-info">
              <span class="name">{{ contect.name }}</span>
              <span>{{ contect.company }}<i class="inline"></i>{{ contect.position }}</span>
            </div>
            <div class="contect-info date">
              <span>{{ contect.newdate }}</span>
              <span class="tips" v-show="contect.newStatus">new</span>
            </div>
          </li>
        </ul>
      </GeminiScrollbar>
    </aside>
    <main v-show="nowId">
      <p class="title">
        <span>{{nowName}}</span>
        <span>{{nowCompany}}</span><i class="inline"></i><span>{{nowDept}}</span>
      </p>
      <main>
        <GeminiScrollbar class="im-container">
          <ul class="im-list">
            <template v-for="im of im_list">
              <li
                v-if="im.userId !== myId"
                class="other"
                :key="im.id">
                <img width="36" :src="im.thumb || require('@/assets/img/default.png')"/>
                <div class="msg-box" v-html="im.text"></div>
              </li>
              <li v-else
                  class="me"
                  :key="im.id">
                <div class="msg-box" v-html="im.text"></div>
                <img width="36" :src="userInfo.thumb || require('@/assets/img/default.png')"/>
              </li>
            </template>
          </ul>
        </GeminiScrollbar>
      </main>
      <footer>
        <quill-editor
          class="editor"
          @change="onTextChange"
          :options="editorConfig1"
          v-model="textTemp"
          @keyup.enter="onSend"
        ></quill-editor>
        <span class="text-btn" v-if="show" @click="sendEmail">发送简历</span>
        <div class="send">
          <p class="desc">按Enter键发送</p>
          <span @click="onSend" :class="{ disabled: !sendable }">发送</span>
        </div>
      </footer>
    </main>
    <main class="empty" v-show="!nowId">
      <p>Tips：与您沟通过的简招者都会在左侧显示</p>
    </main>
  </div>
</template>
<script>
import { quillEditor } from 'vue-quill-editor';
import api from '@/api/chatRoom';
import nginx from '@/assets/nginxconfig';

const emojiIcon = '<svg class="i" viewBox="0 0 24 24"><use href="#emoticon-happy"></use></svg>';
export default {
  name: 'ChatRoom',
  data() {
    return {
      webSocketHeart: null,

      nowName: '',
      nowDept: '',
      nowCompany: '',
      contects: [],
      chosenContect: {
        id: '',
        name: '',
        company: '',
        position: '',
        unread: '1',
      },
      im_list: [],

      editorConfig1: {
        placeholder: '',
        modules: {
          imagePaste: {
            addImageBlob: async (blob, callback) => {
              const formData = new FormData();
              formData.append('image', blob);
              const imageUrl = await this.picUpload(blob);
              callback(imageUrl);
            },
          },
          toolbar: {
            container: ['emoji', 'link', 'image'],
            handlers: {
              emoji() {},
            },
          },
          'emoji-toolbar': true,
          // 'emoji-textarea': true,
          'emoji-shortname': true,
        },
        'emoji-toolbar': {
          buttonIcon: emojiIcon,
        },
      },
      sendable: false,
      textTemp: '',
      wsObj: '',
      keepConnect: null,
      nowId: '',
      myId: '',
      show: true,
      alreadySend: false,
      nowheadpic: '',
    };
  },
  methods: {
    getUserInfo(p, status) {
      const params = new URLSearchParams();
      params.append('userId', p);
      api.getPersonInfoApi(params).then(async (response) => {
        let newS = false;
        if (status === 1) {
          newS = true;
        }
        const datas = response.data.data;
        const nowdate = new Date();
        let ico = '';
        if (datas.remark) {
          ico = nginx.nginxaddress + datas.remark;
        }
        this.contects.push({
          id: datas.id,
          name: datas.realname,
          company: this.getEduName(datas.educated),
          position: this.getExpName(datas.experience),
          newdate: `${nowdate.getMonth() + 1}-${nowdate.getDate()}`,
          newStatus: newS,
          headpic: ico,
        });
      });
    },
    changePerson(p) {
      // console.log(this.contects);
      if (this.nowName === p.name) return;
      this.nowheadpic = p.headpic;
      this.nowId = p.id;
      this.nowName = p.name;
      this.nowCompany = p.company;
      this.nowDept = p.position;
      // eslint-disable-next-line no-param-reassign
      p.newStatus = false;
      this.getMessage(p.id);
    },
    getMessage(otherId) {
      const params = new URLSearchParams();
      params.append('userId', sessionStorage.getItem('userId'));
      params.append('otherId', otherId);
      api.getAllMessageApi(params).then(async (response) => {
        this.im_list = [];
        const datas = response.data.data;
        for (let i = 0; i < datas.length; i += 1) {
          this.im_list.push({
            thumb: this.nowheadpic,
            id: datas[i].businessId,
            userId: datas[i].senderId,
            text: datas[i].message,
          });
        }
        this.$nextTick(() => {
          const scroll = document.querySelector('.im-container .gm-scroll-view');
          scroll.scrollTo(0, scroll.scrollHeight);
        });
      });
    },
    onTextChange({ text }) {
      if (text.trim()) {
        this.sendable = true;
      } else {
        this.sendable = false;
      }
    },
    onSend() {
      if (!this.sendable) return;
      this.textTemp = this.textTemp.replace(/<p><br><\/p>/g, '');
      this.im_list.push({
        id: `text100${Math.random()}`,
        userId: sessionStorage.getItem('userId'),
        text: this.textTemp,
      });
      this.wsObj.send(`send ${this.nowId} ${this.textTemp}`);
      this.textTemp = '';
      this.$nextTick(() => {
        const scroll = document.querySelector('.im-container .gm-scroll-view');
        scroll.scrollTo(0, scroll.scrollHeight);
      });
    },
    getEduName(p) {
      switch (p) {
        case '0':
          return '小学';
        case '1':
          return '初中';
        case '2':
          return '高中';
        case '3':
          return '大专';
        case '4':
          return '本科';
        case '5':
          return '研究生';
        case '6':
          return '博士';
        default:
          return null;
      }
    },
    getExpName(p) {
      switch (p) {
        case '0':
          return '应届生';
        case '1':
          return '一年工作经验';
        case '2':
          return '两年工作经验';
        case '3':
          return '五年工作经验';
        case '4':
          return '十年以上工作经验';
        default:
          return null;
      }
    },
    sendEmail() {
      if (!this.alreadySend) {
        const params = new URLSearchParams();
        params.append('senderId', sessionStorage.getItem('userId'));
        params.append('receiverId', this.nowId);
        api.sendEmailApi(params).then(async () => {
          this.$alert('发送成功');
          this.alreadySend = true;
          this.im_list.push({
            id: `text100${Math.random()}`,
            userId: sessionStorage.getItem('userId'),
            text: '<p>我已经将简历发到您的邮箱</p>',
          });
          this.wsObj.send(`send ${this.nowId} <p>我已经将简历发到您的邮箱</p>`);
          this.$nextTick(() => {
            const scroll = document.querySelector('.im-container .gm-scroll-view');
            scroll.scrollTo(0, scroll.scrollHeight);
          });
        });
      } else {
        this.$alert('请勿重复发送');
      }
    },
    setupWebSocket() {
      // eslint-disable-next-line no-console
      console.log('connecting...');
      const ws = new WebSocket('ws://123.206.41.36:8080/websocket');
      ws.onopen = (res) => {
        // eslint-disable-next-line no-console
        console.log(res);
        clearInterval(this.webSocketHeart);
        ws.send(`bundle ${sessionStorage.getItem('userId')}`);
        this.keepConnect = setInterval(() => {
          ws.send('KEEP CONNECT');
        }, 5000);
      };
      ws.onmessage = (res) => {
        // eslint-disable-next-line no-console
        console.log(this.contects);
        const data = res.data.split('&&');
        if (data[1] === this.nowId) {
          this.im_list.push({
            id: `text100${Math.random() * 50}`,
            thumb: this.nowheadpic,
            userId: data[1],
            text: data[0],
          });
          this.$nextTick(() => {
            const scroll = document.querySelector('.im-container .gm-scroll-view');
            scroll.scrollTo(0, scroll.scrollHeight);
          });
        } else {
          // eslint-disable-next-line no-console
          console.log(this.contects);
          let exist = false;
          for (let i = 0; i < this.contects.length; i += 1) {
            if (this.contects[i].id === data[1]) {
              this.contects[i].newStatus = true;
              exist = true;
              break;
            }
          }
          if (exist === false) {
            this.getUserInfo(data[1], 1);
          }
        }
      };
      ws.onclose = async (e) => {
        // eslint-disable-next-line no-console
        console.log(e);
        this.setupWebSocket();
        this.webSocketHeart = setInterval(this.setupWebSocket, 10000);
      };
      this.wsObj = ws;
    },

    async picUpload(file) {
      const params = new FormData();
      params.append('file', file);
      const res = await api.uploadPic(params);
      return nginx.nginxaddress + res.data.data;
    },
  },
  components: {
    quillEditor,
  },
  computed: {
    userInfo: {
      cache: false,
      get() {
        if (this.$store.getters['user/getUserInfo'].userToken !== null) {
          return this.$store.getters['user/getUserInfo'];
        }
        return null;
      },
    },
  },
  mounted() {
    this.myId = sessionStorage.getItem('userId');
    document.querySelector('.ql-editor').onkeydown = (e) => {
      if (e.keyCode === 13) {
        this.onSend();
      }
    };
    const params = new URLSearchParams();
    params.append('userId', sessionStorage.getItem('userId'));
    api.getMessagePersonApi(params).then(async (response) => {
      const list = response.data.data.messageEntities;
      this.contects = [];
      let thisId = '';
      const nowdate = new Date();
      if (this.$route.query.person) {
        thisId = this.$route.query.person.otherId;
        this.contects.push({
          id: this.$route.query.person.otherId,
          name: this.$route.query.person.emplName,
          company: this.$route.query.person.companyName,
          position: this.$route.query.person.emplJob,
          newdate: `${nowdate.getMonth() + 1}-${nowdate.getDate()}`,
          newStatus: false,
          headpic: '',
        });
      }
      if (response.data.data.role === '0') {
        for (let i = 0; i < list.length; i += 1) {
          let ico = '';
          if (list[i].sysUser.remark) {
            ico = nginx.nginxaddress + list[i].sysUser.remark;
          }
          if (list[i].sysUser.businessId !== thisId) {
            this.contects.push({
              id: list[i].sysUser.businessId,
              name: list[i].sysUser.realname,
              company: list[i].bcompany.name,
              position: list[i].bdept.name,
              newdate: list[i].date,
              newStatus: false,
              headpic: ico,
            });
          }
        }
      } else {
        this.show = false;
        for (let i = 0; i < list.length; i += 1) {
          let ico = '';
          if (list[i].sysUser.remark) {
            ico = nginx.nginxaddress + list[i].sysUser.remark;
          }
          this.contects.push({
            id: list[i].sysUser.businessId,
            name: list[i].sysUser.realname,
            company: this.getEduName(list[i].bcandidate.educated),
            position: this.getExpName(list[i].bcandidate.experience),
            newdate: list[i].date,
            newStatus: false,
            headpic: ico,
          });
        }
      }
    });
    this.setupWebSocket();
  },
  beforeRouteLeave(to, from, next) {
    this.wsCloseable = true;
    this.$alert('正在关闭连接...');
    this.wsObj.onclose = () => {
      this.$alert('关闭成功');
      // eslint-disable-next-line no-console
      console.log('closed');
      next();
    };
    this.wsObj.close();
  },
};
</script>
<style lang="less">
@import url(../../../static/style/site.vars.less);
.chatRoom {
  width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: center;
  align-items: center;
  height: calc(97vh - 50px);
  margin-top: 10px;
  margin-bottom: 10px;
  .title {
    top: 0;
    padding: 15px 25px;
    font-size: 14px;
    border-bottom: 2px solid rgba(145, 155, 172, 0.144);
    position: absolute;
    width: 100%;
    color: #9FA3B0;
    height: 52px;
    box-sizing: border-box;
    &>span {
      margin: 0 9px;
    }
  }
  &>aside {
    width: 35%;
    height: calc(100% - 52px);
    background: #fff;
    border-right: 2px solid rgba(145, 155, 172, 0.144);
    overflow: hidden;
    padding-top: 52px;
    position: relative;
    ul {
      list-style: none;
      height: 100%;
      li {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding: 15px 0;
        padding-left: 23px;
        cursor: pointer;
        &:hover {
          background:#ECF1F7;
          .date {
            background: #ECF1F7;
          }
        }
        &.active {
          background:#ECF1F7;
          .date {
            background: #ECF1F7;
          }
        }
        .contect-info {
          display: flex;
          flex-direction: column;
          font-size: 12px;
          margin-left: 14px;
          color: #B4B8C2;
          .name {
            font-size: 15px;
            margin-bottom: 3px;
            color: rgb(109, 116, 131);
          }
          &.date {
            flex: 1;
            text-align: right;
            height: 41px;
            padding-right: 15px;
            align-items: flex-end;
          }
          .tips {
            width: 30px;
            height: 20px;
            margin-top: 7px;
            color: #fff;
            text-align: center;
            background: #2b85e4;
            box-sizing: border-box;
            padding-top: 3px;
            border-radius: 40px;
          }
        }
        img {
          border-radius: 40px;
        }
      }
    }
  }
  &>main {
    width: 100%;
    background: #fff;
    height: 100%;
    overflow: hidden;
    padding-top: 52px;
    position: relative;
    padding-bottom: 200px;
    box-sizing: border-box;
    main {
      height: 100%;
      ul {
        padding: 20px 32px;
        list-style: none;
        li {
          display: flex;
          margin-top: 30px;
          &>img {
            border-radius: 36px;
          }
          .msg-box {
            margin-top: 2px;
            margin-left: 15px;
            padding: 7px 20px;
            max-width: 504px;
            word-wrap:break-word;
            background: rgba(0, 98, 211, 0.089);
            border-radius: 5px;
            &>p {
              font-size: 14px;
            }
            img {
              max-width: 400px;
            }
          }
          &.other {
            align-items: flex-start;
            justify-content: flex-start;
            .msg-box {
              border-top-left-radius: 0;
            }
          }
          &.me {
            align-items: flex-start;
            justify-content: flex-end;
            .msg-box {
              border-top-right-radius: 0;
              margin-left: 0;
              margin-right: 15px;
            }
          }
        }
      }
    }
    &.empty {
      background: url(https://static.zhipin.com/v2/web/geek/chat/images/icon-welcome.png) center center no-repeat;
      background-color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      &>p {
        text-align: center;
        margin-top: 320px;
        font-size: 12px;
        padding-right: 10px;
      }
    }
    footer {
      position: absolute;
      bottom: 0;
      width: 100%;
      height: 200px;
      .quill-editor {
        border: 0;
        height: 150px;
        .ql-toolbar {
          border: 0;
          border-top: 2px solid rgba(145, 155, 172, 0.144);
        }
        .ql-container {
          border: 0;
          height: calc(150px - 42px);
          .ql-editor {
            padding-top: 0;
            font-family: Helvetica Neue,
                         Helvetica,myFont,Hiragino Sans GB,Microsoft YaHei,SimSun,sans-serif;
            font-size: 16px;
          }
          a {
            color: #000 !important;
            cursor: pointer;
          }
          img {
            max-height: 80px;
          }
        }
      }
      .text-btn {
        position: absolute;
        top: 12px;
        font-size: 13px;
        right: 32px;
        cursor: pointer;
        user-select: none;
        &:hover {
          color: @site-main;
        }
      }
      .send {
        height: 50px;
        padding: 0 30px;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        &>span {
          border: 1px solid @site-main;
          background: @site-main;
          color: #fff;
          font-size: 14px;
          padding: 4px 16px;
          cursor: pointer;
          user-select: none;
          &.disabled {
            background: #fff;
            color: #B4B8C2;
            border: 1px solid #B4B8C2;
            cursor: default;
          }
          &:active {
            background: rgba(0, 98, 211, 0.822);
            &:active {
              background: #fff;
            }
          }
        }
        .desc {
          font-size: 13px;
          margin-right: 14px;
          color: #B4B8C2;
          user-select: none;
        }
      }
    }
  }
  .inline {
    display: inline-block;
    width: 1px;
    height: 12px;
    vertical-align: middle;
    background: #e0e0e0;
    margin: 0 5px;
  }
  #emoji-palette {
    max-width: 400px;
    top: -300px !important;
    left: 15px !important;
  }
}
</style>

